* ======================================
* ------- Program: Distance plot -------
* ======================================

	
	* Args:
	* 1: The network to analyze (e.g. "Fam1")
	* 2: Number of bins outside municipality (e.g. 9)
	* 3: Number of bins inside municipality (e.g. 3)
	* 4: Lower bandwidth for sensitivity plot (e.g. 10)
	* 5: Upper bandwidth for sensitivity plot (e.g. 200)
	* 6: Bandwidth increments for sensitivity plot (e.g. 5)
	* 7: Size of axis titles (e.g. "small")
	* 8: Size of axis labels (e.g. "vsmall")
	* 9: Size of title (e.g. "medsmall")
	* 10: Size of text left right of cutoff (e.g. "tiny")
	* 11: line width (e.g. "medium")
	* 12: marker size (e.g. "medium")
	* 13: Set bottom margin to align plots (e.g. 5.5)
	* 14: Set range of aplot y axis (e.g. 0.06)
	* 15: Set increments of aplot y axis (e.g. 0.02)
	* 16: Set range of bplot y axis (e.g. 0.10)
	* 17: Set increments of bplot yaxis (e.g. 0.05)
	* 18: Plot name (e.g. "Fam1Dist")
	* 19: Plot title (e.g. "Panel A: Family")
	* 20: Outcome variable name
	
* Preliminaries
* =============

	* Verify that we choose enough bins
	capture assert `2' >= 2 & `3' >= 2
	if (_rc) {
		display as error "Error: Choose at least two bins on either side."	
	}

	* generate variables
	qui gen Any = `1'Any
	qui gen Same = `1'Same
	qui gen notSame = 1*(Any == 1 & Same == 0)
	qui gen dist = `1'Pol_dist

	
* Split into bins
* ===============
	
	* create bins
	qui xtile binsXnotSame = dist if notSame == 1, nquantiles(`2')
	qui xtile binsXSame = dist if Same == 1, nquantiles(`3')	

	* bins outside
	forvalues i = 1/`2'{
		qui sum dist if binsXnotSame == `i'	
		capture assert r(N) >= 10 
		if (_rc) {
			display as error "Error: Less than 10 obs in bin: `i' outside."	
		}
		local `i'min_out = r(min)
		local `i'max_out = r(max)
		qui gen bin`i'_out = 1*(dist > ``i'min_out' & dist <= ``i'max_out' ///
			& notSame == 1) // Create bins
		local `i'min_out = round(``i'min_out') // For labels
		local `i'max_out = round(``i'max_out') // For labels
	}

	* bins inside
	forvalues i = 1/`3'{
		qui sum dist if binsXSame == `i'	
		capture assert r(N) >= 10 
		if (_rc) {
			display as error "Error: Less than 10 obs in bin: `i' inside"	
		}
		local `i'min_in = r(min)
		local `i'max_in = r(max)
		qui gen bin`i'_in = 1*(dist >= ``i'min_in' & dist <= ``i'max_in' ///
			& Same == 1) // Create bins
		local `i'min_in = round(``i'min_in') // For labels
		local `i'max_in = round(``i'max_in') // For labels
	}


* Estimate effects
* ================
	
	egen idbsu = group(Voter_id Voter_bsu)
	gen period = 1*(year == 2019)
	xtset idbsu period
	estimates clear
	
	*Run regressions to get mean on each side (main effect is absorbed)
	qui xtreg `20' notSame Same i.period, i(idbsu) fe cluster(Voter_bsu)
	local mean_left = _b[notSame]
	local mean_right = _b[Same]
	local lineend_out = `2' + 0.2
	local linestart_in = `2' + 0.8
	local lineend_in = `2' + `3' + 0.2

	* Bin regression (main network effect is absorbed)
	qui xtreg `20' bin*_* i.period, i(idbsu) fe cluster(Voter_bsu)


* Plot logistics
* ==============

	* Xlabels
	forvalues i = 2/`2'{
		local i_rev = `2' + 1 - `i'
		local lab_out = `"`lab_out' `i' "``i_rev'max_out' - ``i_rev'min_out'""'
		local order_out 
	}
	local lab_out = `"1 "``2'min_out' +"`lab_out'"' // First bin
	local end = `2' + `3'
	local i_cont = `2' + 1
	local n_in = `end' - 1 
	forvalues i = `i_cont'/`n_in'{
		local i_sub = `i' - `i_cont' + 1
		local lab_in = `"`lab_in' `i' "``i_sub'min_in' - ``i_sub'max_in'""'
	}
	local lab_in = `"`lab_in' `end' "``3'min_in' +""' // Last bin
	local xlab = `"`lab_out'`lab_in'"' // Combine

	* order coefficients
	forvalues i = `2'(-1)1{
		local order_out = `"`order_out' *`i'*_out"'
	}
	forvalues i = 1/3{
		local order_in = `"`order_in' *`i'_in*"'
	}
	local order = `"`order_out'`order_in'"'

	* compute coordinates
	local xline = `2' + 0.5
	local txtcoord_xl = `2' + 0.4
	local txtcoord_xr = `2' + 0.6
	local txtcoord_y  = -`14'


* Make plot A
* ===========

	coefplot, ///
		vertical drop(_cons *period) msymbol(O) msize(`12') ///
			ciopts(lwidth(`11')) ///
		order(`order') xlab(`xlab', angle(45) labsize(`8') gmin gmax) ///
		ytitle("Coefficient estimate", size(`7')) ///
		ylab(-`14'(`15')`14', format(%9.2g) labsize(`8') gmin gmax) ///
		yline(0, lpattern(solid) lwidth(`11') ) ///
		xtitle("Distance in km between voter and candidate", size(`7')) ///
		xline(`xline', lwidth(`11')) ///
		addplot(	///
			(scatteri `mean_left' 0.8 `mean_left' `lineend_out', ///
				recast(connected) lpattern(solid) lwidth(`11') ///
				lcol(cranberry) msymbol(none)) ///
			(scatteri `mean_right' `linestart_in' `mean_right' `lineend_in', ///
				recast(connected) lpattern(solid) lwidth(`11') ///
				lcol(cranberry) msymbol(none))) ///
		text(`txtcoord_y' `txtcoord_xl' "Different district {&larr}", ///
			placement(nw) size(`10') color(gs6)) ///
		text(`txtcoord_y' `txtcoord_xr' "{&rarr} Same district", ///
			placement(ne) size(`10') color(gs6)) ///
		title("Distance bins", size(`9')) ///
		name(panelA,replace) scheme(plotplain)


* Sensitivity analysis
* ====================

	local ci_u_max = 0
	local ci_l_max = 0
	forvalues i = `5'(-`6')`4'{
		qui xtreg `20' Any Same i.period if dist == . | ///
			dist <`i', i(idbsu) fe cluster(Voter_bsu)
		local coef = _b[Same]
		local se = _se[Same]
		local ci_u = `coef' + 1.96*`se'
		local ci_l = `coef' - 1.96*`se'
		local matrix = `"`i' , `coef' , `ci_u' , `ci_l' `matrix' "'
		if `i' != `4'{				// Add line break until last
			local matrix = `" \ `matrix' "'	
		}
	}



* Make plot B
* ===========

	matrix input coefmat = (`matrix')
	svmat coefmat
	rename coefmat1 bw
	rename coefmat2 b
	rename coefmat3 ci_u
	rename coefmat4 ci_l	

	twoway	(rarea ci_u ci_l bw, col(gray%25)) ///
		(scatter b bw, recast(connected) lcol(cranberry) ///
			lpattern(solid) msymbol(none) lwidth(`11')) ///
		(rarea ci_u ci_l bw, col(gray%25)) ///
		(scatter b bw, recast(connected) lcol(cranberry) ///
			lpattern(solid) msymbol(none) lwidth(`11')), ///
	xlab(0(20)`5', nogrid labsize(`8') angle(45) gmin gmax) ///
	xtitle(Bandwidth, margin(0 0 1 `13') size(`7')) ///
	ylab(-`16'(`17')`16', format(%9.2g)  labsize(`8') gmin gmax) ///
		yline(0, lpattern(solid) lwidth(`11')) ///
	title("Varying bandwidth", size(`9')) ///
	legend(off) name(panelB, replace) scheme(plotplain)

	drop bw b ci_u ci_l Any* Same* notSame* dist bin*

	
* Combine plots
* =============

	graph combine panelA panelB, ///
		xsize(8) scheme(plotplain) col(2) title("`19'") ///
		name(`18', replace) graphregion(margin(0 0 0 0))
